// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2025-01-09

package info

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"gomq/app/authorizer"
	"gomq/app/errs"
	"gomq/app/models"
	"gomq/app/services"
)

type Logic struct {
	authentication *authorizer.Authentication
	response       *Response
}

func New() logics.Logical {
	return &Logic{
		response: &Response{},
	}
}

func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	var has bool

	// Get authentication from token.
	if o.authentication, has = authorizer.New().Get(i); !has {
		err = errs.ErrUserUnauthorized
		return
	}

	// Generate response.
	o.response.WithPermissions(o.authentication.Roles)
	return
}

func (o *Logic) Run(ctx context.Context, i iris.Context) (res result.Result) {
	var (
		err     error
		service = services.NewUserService()
		user    *models.User
	)

	res = result.New()

	// Read user by id.
	if user, err = service.GetById(ctx, o.authentication.Id); err != nil {
		res.WithError(errs.ErrDatabaseError)
		return
	}

	// Return error if user not found by id.
	if user == nil {
		res.WithError(errs.ErrUserNotFound)
		return
	}

	// Return error if user was disabled.
	if user.Status.Disabled() {
		res.WithError(errs.ErrUserStatusDisabled)
		return
	}

	// Return error if user was locked.
	if user.Status.Locked() {
		res.WithError(errs.ErrUserStatusLocked)
		return
	}

	// Update response.
	o.response.WithUser(user)

	res.With(o.response)
	return
}
